
#ifndef RESOURCEMANAGER_H
#define RESOURCEMANAGER_H

namespace ETM
{
	namespace Resources
	{
		template<class T>
		class ResourceManager
		{
		public:
			//Define a Resource as a pair of an id and a resource.
			typedef std::pair<std::string, T*> Resource;
			//Define a ResourceMap as a map of id's and resources.
			typedef std::map<std::string, T*> ResourceMap;

		private:
			ResourceMap resourceMap;

			//Find a Resource in the resource map, if not found it returns NULL.
			T* Find(const std::string& id)
			{
				T* resource = NULL;

				ResourceMap::iterator it = resourceMap.find(id);

				if(it != resourceMap.end())
					resource = it->second;

				return resource;
			}

		protected:
			//Virtual function that a Manager class should override.
			virtual T* Load(const std::string& id) = 0;

		public:
			ResourceManager()
			{

			}

			virtual ~ResourceManager()
			{
				ReleaseAllResources();
			}

			//Gets a resource, if not found in the map it is loaded.
			T* GetResource(const std::string& id)
			{
				T* resource = Find(id);

				if(resource == NULL)
				{
					resource = Load(id);

					if(resource != NULL)
						resourceMap.insert(Resource(id, resource));
				}

				return resource;
			}

			//Releases a loaded resource.
			void ReleaseResource(const std::string& id)
			{
				T* resource = find(id);

				if(resource != NULL)
				{
					delete resource;
					resourceMap.erase(resourceMap.find(id));
				}
			}

			//Releases all the loaded resources.
			void ReleaseAllResources()
			{
				while(resourceMap.begin() != resourceMap.end())
				{
					delete resourceMap.begin()->second;
					resourceMap.erase(resourceMap.begin());
				}
			}
		};
	}
}

#endif